package com.synergy.stockflow.warehouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.synergy.stockflow.warehouse.mapper.WarehouseMapper;
import com.synergy.stockflow.warehouse.entity.Warehouse;
import com.synergy.stockflow.warehouse.service.WarehouseService;

@Service
public class WarehouseServiceImpl extends ServiceImpl<WarehouseMapper, Warehouse> implements WarehouseService {

    private static final Logger log = LoggerFactory.getLogger(WarehouseServiceImpl.class);

    @Override
    public String getMaxWarehouseId() {
        QueryWrapper<Warehouse> queryWrapper = new QueryWrapper<>();
        // 使用lambda表达式方式选择字段，兼容更多版本
        queryWrapper.lambda().select(Warehouse::getWarehouseId);
        queryWrapper.orderByDesc("warehouse_id").last("limit 1");

        Warehouse maxWarehouse = baseMapper.selectOne(queryWrapper);
        return (maxWarehouse == null || maxWarehouse.getWarehouseId() == null)
                ? "WH-000"
                : maxWarehouse.getWarehouseId();
    }

    @Override
    public String generateNextWarehouseId() {
        try {
            String maxId = getMaxWarehouseId();
            // 修复拼写错误 lastIndexOf 改为 lastIndexOf
            String numStr = maxId.substring(maxId.lastIndexOf("-") + 1);
            int nextNum = Integer.parseInt(numStr) + 1;
            String formattedNum = String.format("%03d", nextNum);
            return "WH-" + formattedNum;
        } catch (Exception e) {
            log.error("生成仓库ID异常：", e);
            return "WH-001";
        }
    }
}